const pathToRegExp = require("path-to-regexp");
function Layer(path, handler) {
  this.path = path;
  this.regexp = pathToRegExp(this.path, (this.keys = []));
  this.handler = handler;
}
Layer.prototype.match = function (pathname) {
  // 除了路由的匹配还有中间件的匹配
  if (this.path == pathname) {
    return true;
  }
  if (this.route) {
    // 路由
    let matches = pathname.match(this.regexp);
    if (matches) {
      let values = matches.slice(1); // [1,2]
      this.params = this.keys.reduce(
        (memo, current, index) => ((memo[current.name] = values[index]), memo),
        {}
      );
      // layer.params = {id:1,name:2}
      return true;
    }
  }

  if (!this.route) {
    if (this.path === "/") {
      return true;
    }
    return pathname.startsWith(this.path + "/");
  }
};
Layer.prototype.handle_error = function (err, req, res, next) {
  if (this.handler.length == 4) {
    this.handler(err, req, res, next);
  } else {
    // 普通中间件
    next(err);
  }
};
Layer.prototype.handle_request = function (req, res, next) {
  this.handler(req, res, next);
};

module.exports = Layer;

// Router外层中存放的是 layer (路径，dispatch)
// Route 是里层的 存放的是layer (不考虑路径， 用户真正执行的逻辑)
